<template>
  <div class="cart">
    <h2>购物车</h2>

    <!-- 地址选择下拉框 -->
    <el-select v-model="selectedAddress" placeholder="选择地址">
      <el-option
        v-for="address in addressList"
        :key="address.id"
        :label="`${address.address} `"
        :value="address.id"
      ></el-option>
    </el-select>

    <el-table
      :data="cartItems"
      ref="table"
      style="width: 100%"
      @selection-change="updateTotalPrice"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="shop_img" label="商品图片" width="120">
        <template slot-scope="scope">
          <img
            :src="getImageUrl(scope.row.shop_img)"
            alt="商品图片"
            class="product-image"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="shop_name"
        label="商店名称"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="shop_description"
        label="商品简介"
        width="300"
      ></el-table-column>
      <el-table-column label="数量" width="100">
        <template slot-scope="scope">
          <div class="quantity-controls">
            <el-button
              @click="changeQuantity(scope.row.product_id, -1)"
              type="danger"
              size="small"
              >-</el-button
            >
            <span>{{ scope.row.quantity }}</span>
            <el-button
              @click="changeQuantity(scope.row.product_id, 1)"
              type="primary"
              size="small"
              >+</el-button
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="shop_price" label="单价" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.shop_price }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            @click="removeFromCart(scope.row.product_id)"
            type="danger"
            size="small"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="total">
      <span>总计: {{ totalPrice }} 元</span>
      <el-button
        type="success"
        @click="openPaymentDialog"
        style="margin-left: 20px"
        >支付</el-button
      >
    </div>

    <!-- 支付弹窗 -->
    <el-dialog title="支付确认" :visible.sync="paymentDialogVisible">
      <p>您选择的商品总计: {{ totalPrice }} 元</p>
      <p>请确认支付信息。</p>
      <span>支付方式: <strong>第三方支付</strong></span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      cartItems: [], // 购物车商品列表
      selectedItems: [], // 选中的商品列表
      paymentDialogVisible: false, // 控制支付弹窗的显示
      orderId: null, // 用于存储订单 ID
      addressList: [], // 地址列表
      selectedAddress: null, // 选中的地址 ID
    };
  },
  computed: {
    totalPrice() {
      return this.cartItems
        .reduce((total, item) => {
          if (this.selectedItems.includes(item.product_id)) {
            return total + item.shop_price * item.quantity;
          }
          return total;
        }, 0)
        .toFixed(2); // 计算总价，保留两位小数
    },
  },
  methods: {
    fetchCartItems() {
      const userId = localStorage.getItem("userId");
      axios
        .post("/GetCartByuserID", { user_id: userId }) // 替换为你的 API 地址
        .then((response) => {
          if (response.data.code === 200) {
            this.cartItems = response.data.data; // 假设返回的数据结构
            console.log("购物车返回的数据", response.data);
          } else {
            this.$message.error("获取购物车数据失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取购物车数据失败:", error);
          this.$message.error("获取购物车数据失败，请重试。");
        });
    },
    fetchAddresses() {
      const userId = localStorage.getItem("userId");
      axios
        .get(`/Address/Sel?user_id=${userId}`) // 调用获取地址的接口
        .then((response) => {
          if (response.data.code === 200) {
            this.addressList = response.data.data; // 假设返回的数据结构
          } else {
            this.$message.error("获取地址失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取地址失败:", error);
          this.$message.error("Address获取地址失败，请重试。");
        });
    },
    removeFromCart(productId) {
      const userId = localStorage.getItem("userId");
      axios
        .post("/DelProduct", { user_id: userId, product_id: productId }) // 调用移除商品的接口
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("商品已移除！");
            this.fetchCartItems(); // 重新获取购物车数据
          } else {
            this.$message.error("移除失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("移除购物车商品失败:", error);
          this.$message.error("移除失败，请重试。");
        });
    },
    changeQuantity(productId, change) {
      const userId = localStorage.getItem("userId");
      const item = this.cartItems.find((item) => item.product_id === productId);
      if (item) {
        const newQuantity = item.quantity + change;
        if (newQuantity < 1) {
          this.$message.warning("数量不能小于1");
          return;
        }
        // 更新购物车数量的 API 调用
        const apiEndpoint = change > 0 ? "/AddIntoCart" : "/ReduceProductNum";
        axios
          .post(apiEndpoint, {
            user_id: userId,
            product_id: productId,
            quantity: newQuantity,
          })
          .then((response) => {
            if (response.data.code === 200) {
              item.quantity = newQuantity; // 更新本地数量
              this.$message.success("数量更新成功！");
            } else {
              this.$message.error("更新数量失败: " + response.data.msg);
            }
          })
          .catch((error) => {
            console.error("更新购物车数量失败:", error);
            this.$message.error("更新数量失败，请重试。");
          });
      }
    },
    updateTotalPrice() {
      // 更新选中的商品列表
      const selectedRows = this.$refs.table.selection;
      this.selectedItems = selectedRows.map((item) => item.product_id);
    },
    openPaymentDialog() {
      // 更新选中的商品列表
      const selectedItems = this.cartItems.filter((item) =>
        this.selectedItems.includes(item.product_id)
      );

      if (selectedItems.length === 0) {
        this.$message.warning("请至少选择一个商品进行支付");
        return;
      }

      if (!this.selectedAddress) {
        this.$message.warning("请先选择一个地址");
        return;
      }

      // 获取登录用户的 ID
      const customerId = localStorage.getItem("userId"); // 从 localStorage 获取用户 ID

      // 准备要发送的数据
      const orderData = {
        address: this.selectedAddress, // 使用选中的地址 ID
        customer_id: customerId, // 使用实际的客户 ID
        total_price: this.totalPrice, // 计算的总价
        status: "待付款",
        order_items: selectedItems.map((item) => ({
          product_id: item.product_id,
          quantity: item.quantity,
          price: item.shop_price,
        })),
      };

      // 发送 POST 请求到后端
      axios
        .post("/orders", orderData)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单创建成功！");
            this.orderId = response.data.data; // 假设返回的订单 ID
            this.paymentDialogVisible = true; // 显示支付弹窗
          } else {
            this.$message.error("订单创建失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("创建订单失败:", error);
          this.$message.error("创建订单失败，请重试。");
        });
    },
    confirmPayment() {
      // 发送 PUT 请求更新订单状态
      axios
        .put(`/orders/${this.orderId}/status?status=2`)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("支付成功！感谢您的购买。");
            this.paymentDialogVisible = false; // 关闭支付弹窗
            // 移除已支付的商品
            this.selectedItems.forEach((productId) => {
              this.removeFromCart(productId); // 移除每个选中的商品
            });
          } else {
            this.$message.error("支付失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("更新订单状态失败:", error);
          this.$message.error("支付失败，请重试。");
        });
    },
    getImageUrl(imageData) {
      // 将二进制文件流转换为可用的 URL
      return `data:image/jpeg;base64,${imageData}`;
    },
  },
  mounted() {
    this.fetchCartItems(); // 组件挂载时获取购物车数据
    this.fetchAddresses(); // 组件挂载时获取地址数据
  },
};
</script>

<style scoped>
.cart {
  padding: 20px;
}

.total {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity-controls span {
  margin: 0 10px;
}

.product-image {
  width: 100%;
  /* 设置图片宽度 */
  height: auto;
  /* 自适应高度 */
  border-radius: 5px;
  /* 圆角 */
}
</style>
